<?php

namespace IMT\AccountBundle\Controller;

use IMT\AccountBundle\Entity\AccountGmail;

use IMT\AccountBundle\Entity\AccountIMT;

use IMT\UserBundle\Entity\Group;
use IMT\AccountBundle\Entity\Account;
use IMT\AccountBundle\Form\AccountFormHandler;
use IMT\AccountBundle\Form\AccountFormType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Acl\Domain\ObjectIdentity;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Acl\Domain\UserSecurityIdentity;
use Symfony\Component\Security\Acl\Permission\MaskBuilder;


class DefaultController extends Controller
{
    
    public function indexAction()
    {
    	$user = $this->container->get('security.context')->getToken()->getUser();

    	$accountsIMT = $this->getDoctrine()->getRepository('IMTAccountBundle:AccountIMT')->findBy(array(
    			'active' => true,
    			'user' => $user
    	));

    	$accountsGmail = $this->getDoctrine()->getRepository('IMTAccountBundle:AccountGmail')->findBy(array(
    			'active' => true,
    			'user' => $user
    	));
    	
//     	$accounts = $this->getDoctrine()->getRepository('IMTAccountBundle:Account')->findBy(array(
//     		'user' => $user
//     	));
    	
    	return $this->render('IMTAccountBundle:Profile:index.html.twig', array(
    			'accounts_imt' => $accountsIMT,
    			'accounts_gmail' => $accountsGmail
    	));
    }
    
    public function listAction($active)
    {
    	$user = $this->container->get('security.context')->getToken()->getUser();
    
    	$accounts = $this->getDoctrine()->getRepository('IMTAccountBundle:Account')->findBy(array(
    		'active' => $active,
    		'user' => $user
    	));
    	 
    	return $this->render('IMTAccountBundle:Default:list.html.twig', array('accounts' => $accounts, 'vue' => 'agenda'));
    }
    
    public function listAllAction($id)
    {
    	$user = $this->container->get('security.context')->getToken()->getUser();
    	$accounts = $this->getDoctrine()->getRepository('IMTAccountBundle:Account')->findAllByUser($user);
    	
    	foreach($accounts as $account){
    		$form = $this->createForm(new AccountFormType(), $account);
    		$account->editForm = $form->createView();
    	}
    	
    	return $this->render('IMTAccountBundle:Default:list.html.twig', array(
    			'accounts' => $accounts, 
    			'vue' => 'profil',
    			'openAccount' => $id
    	));
    }
    
    public function listParticipantsAction(){
    	$participants = array();
    	$request = $this->getRequest();
    
    	if ('POST' == $request->getMethod()){    			
    		$accounts = explode(';', $request->request->get('listAccount'));
    			
    		if(sizeof($accounts) > 0 && $accounts[0] != ''){
    			foreach($accounts as $accountId){
    				if(intval($accountId) != 0){
    					$account = $this->getDoctrine()->getRepository('IMTAccountBundle:Account')->find($accountId);
    					foreach($account->getParticipants() as $participant){
    						$participants[] = $participant;
    					}
    				}
    			}
    		}
    	}
    
    	return $this->render('IMTAccountBundle:Participant:list.html.twig', array('participants' => $participants));
    }
    
    public function editAction($id){
    	$user = $this->container->get('security.context')->getToken()->getUser();
    	$em = $this->getDoctrine()->getEntityManager();
    	$securityContext = $this->get('security.context');
    	
    	$accounts = $this->getDoctrine()->getRepository('IMTAccountBundle:Account')->findAllByUser($user);
    	   	
    	foreach($accounts as $account){
    		if($account->getId() == $id){
    			// check for edit access
    			if (false === $securityContext->isGranted('EDIT', $account))
    			{
    				throw new AccessDeniedException();
    			}
    			
	    		$form = $this->createForm(new AccountFormType(), $account);
	    		$formHandler = new AccountFormHandler($form, $this->getRequest(), $em);
	    		 
	    		$process = $formHandler->process();
	    		if ($process) {
	    			$editAccount = $form->getData();
	    			$group = $editAccount->getGroup();
	    			$group->setTitle($editAccount->getTitle());
	    			$group->setName(md5($user->getId().$editAccount->getTitle()));
	    			
	    			$em->persist($group);
	    			$em->flush();
	    			
	    			$this->get('session')->setFlash('alert-success', 'Le compte '.$account->getTitle().' a été modifié !');
	    			 
	    			return $this->redirect($this->generateUrl('profil_comptes'));
	    		}
	    		
	    		$this->get('session')->setFlash('alert-danger', 'Des erreurs empêchent la modification du compte');
	    		return $this->redirect($this->generateUrl('profil_comptes'));
    		}
    	}
    	
    	$this->get('session')->setFlash('alert-danger', 'Impossible de modifier le compte');
    	return $this->redirect($this->generateUrl('profil_comptes'));
    }
    
    public function newAction(){
    	$request = $this->getRequest();
    	$em = $this->getDoctrine()->getEntityManager();
		$user = $this->container->get('security.context')->getToken()->getUser();
    	
    	$account = new Account();
    	$account->setActive(true);
		$account->setUser($user);
    	
    	$accountType = $this->getDoctrine()
    		->getRepository('IMTAccountBundle:AccountType')
    		->find(intval($this->container->getParameter('default_account_id')));
    	$account->setAccountType($accountType);
    	
    	$form = $this->createFormBuilder($account)
	    	->add('title', 'text')
	    	->add('color', 'choice', array(
            	'choices' => array(
            		'fc-event-blue' => 'Bleu', 
            		'fc-event-green' => 'Vert',
            		'fc-event-azul' => 'Bleu clair',
            		'fc-event-red' => 'Rouge',
            		'fc-event-black' => 'Noir',
            		'fc-event-orange' => 'Orange'
            	)
            ))
            ->add('username', 'text', array('required'=> false))
        	->add('password', 'password', array('required'=> false))
	    	->getForm();
    	
    	if('POST' == $request->getMethod()){
	    	$formHandler = new AccountFormHandler($form, $this->getRequest(), $em);
	    	$process = $formHandler->process(false);
	    	if ($process) {
	    		$account = $form->getData();
	    		
	    		$group = new Group();
	    		$group->setName(md5($user->getId().$account->getTitle()));
	    		$group->setTitle($account->getTitle());
	    		$group->setAccount($account);
	    		$account->setGroup($group);
	    		
	    		$em->persist($account);
	    		$em->flush();
	    		
	    		// creating the ACL
	    		$aclProvider = $this->get('security.acl.provider');
	    		$objectIdentity = ObjectIdentity::fromDomainObject($account);
	    		$acl = $aclProvider->createAcl($objectIdentity);
	    		
	    		// retrieving the security identity of the currently logged-in user
	    		$securityContext = $this->get('security.context');
	    		$user = $securityContext->getToken()->getUser();
	    		$securityIdentity = UserSecurityIdentity::fromAccount($user);
	    		
	    		// grant owner access
	    		$acl->insertObjectAce($securityIdentity, MaskBuilder::MASK_VIEW);
	    		$aclProvider->updateAcl($acl);
	    		
	    		$this->get('session')->setFlash('alert-success', 'Le compte '.$account->getTitle().' a été créé !');
	    	} else {
	    		$this->get('session')->setFlash('alert-danger', 'Une erreur a empêché la création du compte');
	    	}
	    	
	    	return $this->redirect($this->generateUrl('profil_comptes'));
    	}
    	
    	return $this->render('IMTUserBundle:Account:list_account.html.twig', array(
				'newAccountForm' => $form->createView()
		));
    }
    
	public function deleteMultiAction($listIds)
    {
    	if($listIds == ''){
    		$this->get('session')->setFlash('warning', 'Aucun compte n\'a été selectionné');
    	} else {
    		$arrayIds = explode(',', $listIds);
    		$countDeleted = 0;
    		$totalDelete = 0;
    		 
    		$em = $this->getDoctrine()->getManager();
    		 
    		foreach($arrayIds as $id){
    			$id = intval($id);
    			 
    			if($id != 0){
    				$totalDelete++;
    				$entity = $em->getRepository('IMTAccountBundle:Account')->find($id);
    					
    				if ($entity) {
    					$em->remove($entity);
    					$em->flush();
    					$countDeleted++;
    				}
    			}
    		}
    		 
    		if($countDeleted == $totalDelete)
    			$this->get('session')->setFlash('success', ($totalDelete == 1) ? 'Le compte a été supprimé' : 'Les comptes ont été supprimés');
    		else
    			$this->get('session')->setFlash('error', ($totalDelete == 1) ? 'Le compte n\'a pas pu être supprimé' : 'Touts les comptes n\'ont pas pu être supprimés');
    	}
    
    	return $this->redirect($this->generateUrl('account_home'));
    }
}
